package com.tinelion.flyer.controller;


import com.tinelion.flyer.service.UserService;
import com.tinelion.flyer.tools.Md5Util;
import com.tinelion.flyer.tools.SendEmail;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;


@RestController
@Slf4j
public class UserController {

    Map<String,String> map=new ConcurrentHashMap<>();

    @Autowired
    private JavaMailSender sender;

    @Autowired
    ExecutorService pool;

    @Autowired
    UserService userService;


    @GetMapping("/login")
    public String login(String userName, String password) {
        return userService.login(userName, password);
    }

    @RequestMapping("/logOut")
    public String logOut() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }


    @RequestMapping("/register")
    public Object add(String email,String userName ,String password, String objs,String role) {

        log.info(email);
        log.info(password);
        log.info(String.valueOf(objs));
        log.info(String.valueOf(map.get(email)));

        if((map.get(email)).equals(objs)){
                int ch = userService.add(email,userName,password,role);
                if (ch == 1) {
                    return "成功";
                }
          return "该用户名已经被使用！";
        }
        return "验证码为空或验证码错误！";
    }

    @GetMapping("/email")
    public void sendEmail(String email){

        String code= Md5Util.random();
        log.info(code);
        map.put(email,code);
        SendEmail emails=new SendEmail(sender,"1101648204@qq.com",email,code);
        pool.submit(emails);
    }

}
